package com.example.controller;

import com.example.model.Review;
import com.example.service.ReviewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.Authentication;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api")
public class ReviewController {

    private final ReviewService reviewService;
    private static final Logger logger = LoggerFactory.getLogger(ReviewController.class);

    public ReviewController(ReviewService reviewService) {
        this.reviewService = reviewService;
    }

    @PostMapping("/products/{productId}/reviews")
    public ResponseEntity<Review> addReview(@PathVariable String productId, @RequestBody Review review, Authentication authentication) {
        try {
            if (authentication == null || !authentication.isAuthenticated()) {
                return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
            }
            Review createdReview = reviewService.createReview(review, productId, authentication);
            return new ResponseEntity<>(createdReview, HttpStatus.CREATED);
        } catch (IOException e) {
            logger.error("Error adding review for product " + productId, e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/products/{productId}/reviews")
    public ResponseEntity<List<Review>> getReviewsForProduct(@PathVariable String productId) {
        try {
            List<Review> reviews = reviewService.getReviewsByProductId(productId);
            return ResponseEntity.ok(reviews);
        } catch (IOException e) {
            logger.error("Error fetching reviews for product: " + productId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // Add other API endpoints here (GET, DELETE)
} 